import json
import random
import os
import shutil

from django.conf import settings
from django.contrib.auth.hashers import make_password, check_password

from Shop.models import Order
# from django.contrib.auth.models import User
from .models import MyUser as User
from django.core.mail import send_mail
from django.http import HttpResponse, JsonResponse
from django_redis import get_redis_connection
from django.contrib.auth.models import Group

def Register(request):
    print("注册ing")
    if request:
        print("ok")
    data = json.loads(request.body.decode('utf-8'))
    username = data.get('username')
    password = data.get('password')
    user_email = data.get('email')
    identity = data.get('identity')
    print(username, password, user_email, identity)
    one_user_username = User.objects.filter(username=username)
    one_user_email = User.objects.filter(email=user_email)
    if one_user_username:
        return HttpResponse('用户名已存在')
    if one_user_email:
        return HttpResponse('该邮箱已被注册')
    # 将数据存入数据库
    password = make_password(password)
    user = User()
    user.username = username
    user.password = password
    user.email = user_email
    user.is_staff = identity
    user.save()
    if identity ==1:
        group = Group.objects.get(id=1)
        user.groups.add(group)
    # 使用默认的头像
    img_path = os.path.join(settings.MEDIA_ROOT, settings.AVATAR_URL.strip('/'), str(user.id) + ".jpg")
    default_path = os.path.join(settings.MEDIA_ROOT, settings.AVATAR_URL.strip('/'), "default.jpg")

    shutil.copyfile(default_path, img_path)

    return HttpResponse('注册成功')


def Login(request):
    data = json.loads(request.body.decode('utf-8'))
    username = data.get('username')
    password = data.get('password')
    identity = data.get('identity')
    # 对password进行加密
    # user = User.objects.get(username=username)
    print(username, password, identity)
    user_list = User.objects.filter(username=username, is_staff=identity)

    if len(user_list) == 0:
        return HttpResponse('用户名不存在', status=250)
    user = user_list[0]
    if user:
        if check_password(password, user.password):
            # return HttpResponse('登录成功')
            # 登录成功后需要返回用户的id和用户名
            data = {'id': user.id, 'username': user.username, 'email': user.email, 'identity': user.is_staff,
                    'date_joined': user.date_joined}
            return JsonResponse(data, json_dumps_params={"ensure_ascii": False})
    return HttpResponse('用户名或密码错误', status=250)


def updateUser(request):
    data = json.loads(request.body.decode('utf-8'))
    user_id = data.get('user_id')
    nickname = data.get('nickname')
    user = User.objects.filter(id=user_id).first()
    if user is None:
        return HttpResponse('用户不存在', status=250)
    user.nickname = nickname
    user.save()
    data = {'id': user.id, 'username': user.username, 'email': user.email, 'identity': user.is_staff,
            'date_joined': user.date_joined}
    return JsonResponse(data, json_dumps_params={"ensure_ascii": False})

def getCount(request):
    print("111111111111111111")
    user_id = request.GET.get('user_id')
    # 获取收藏数量
    favorite_count = User.objects.get(id=user_id).favorite_set.count()
    # 根据用户id获取对应的订单,获取status_buyer为待付款的订单
    wait_pay_orders = Order.objects.filter(user_id=user_id, status_buyer='待付款').count()
    already_pay_orders = Order.objects.filter(user_id=user_id, status_buyer='已付款').count()
    data = {'favorite_total': favorite_count, 'not_pay_total': wait_pay_orders,'pay_total':already_pay_orders}
    # 获取已支付订单数量
    return JsonResponse(data, json_dumps_params={"ensure_ascii": False})
def uploadAvatar(request):
    # 获取前端发来的的file对象
    file = request.FILES.get('file')
    user_id = request.POST.get('user_id')
    # 先判断用户的头像文件是否存在,存在则覆盖原图片
    base_path = os.path.join(settings.MEDIA_ROOT, settings.AVATAR_URL.strip('/'),
                             str(user_id))
    # 检查文件类型
    # file_extension = '.png' if file.name.endswith('.png') else '.jpg'
    file_extension = '.jpg'
    # 完整的文件路径
    file_path = base_path + file_extension

    # 如果文件存在，则先删除原有文件
    if os.path.exists(file_path):
        os.remove(file_path)

        # 保存新的头像文件
    with open(file_path, 'wb+') as destination:
        for chunk in file.chunks():
            destination.write(chunk)

    return HttpResponse('上传成功')


def send_email(request):
    email = request.GET.get('email')
    print(email)
    user = User.objects.filter(email=email)
    if user:
        code = "{:06d}".format(random.randint(0, 999999))
        message = '您的验证码是：' + str(code)
        send_mail(subject='商城——找回密码', message=message, from_email=settings.EMAIL_HOST_USER,
                  recipient_list=[email])
        # COOKIE验证码设置5分钟有效
        conn = get_redis_connection()
        conn.set(email, code, 300)

        return HttpResponse('验证码已发送，请注意查收')

    else:
        return HttpResponse('该邮箱未注册')

    # 生成六位随机验证码 000000-999999的字符串


def ModifyPassword(request):
    data = json.loads(request.body.decode('utf-8'))
    email = data.get('email')
    password = data.get('newpwd')
    code = data.get("testcode")
    print(email, password, code)
    conn = get_redis_connection()
    print("here")
    print(conn.get(email))
    cookie_code = str(conn.get(email), encoding='utf-8')
    print(cookie_code)
    if code != cookie_code:
        return HttpResponse("验证码错误")

    password = make_password(password)

    user = User.objects.get(email=email)

    if user is None:
        return HttpResponse("该邮箱未注册")
    print(user)
    user.password = password
    user.save()
    return HttpResponse("修改成功")


def test_django_redis(request):
    # 可以直接从连接池中拿到连接
    conn = get_redis_connection()
    conn.set("lyy", "654987", 300)

    age = str(conn.get('lyy'), encoding='utf-8')

    return HttpResponse('人的年龄是：%s' % age)


from django.shortcuts import render

# Create your views here.
